import os
import time

# 获取cpu的运行总时间信息
def get_cpu_time():
    # 读取/proc/stat
    with open('/proc/stat', encoding='utf-8') as file:
        content = file.readline().strip('\n')
    cpu_info = list(filter(None,content.split(" ")))
    cpu_time = 0
    for i in range(1, len(cpu_info)):
        cpu_time += int(cpu_info[i])
    return cpu_time

# 获取当前全部进程信息
''' 
    一个进程的信息存在一个字典中，键为标记
    eg: {'pid':1234, 'comm':kinsing, ...}
    所有的进程存放在一个大字典中，键为pid
    eg:{pid1:dict1, pid2:dict2, ...}
'''
def get_proc_info(old_procs):
    # 遍历/proc/<pid>/stat
    dirs = os.listdir("/proc")
    # 全部进程的列表
    procs = old_procs
    for i in range(0, len(dirs)):
        if dirs[i].isdigit() :
            stat_path = "/proc/" + dirs[i] + "/stat"
            with open(stat_path, encoding='utf-8') as file:
                content = file.readline().strip('\n')
            cmdline_path = "/proc/" + dirs[i] + "/cmdline"
            with open(cmdline_path, encoding='utf-8') as file:
                cmdline = file.readline()
            proc_info = list(filter(None,content.split(" ")))
            proc = {}
            proc['pid'] = int(proc_info[0])
            proc['cmdline'] = cmdline
            proc['utime'] = int(proc_info[13])
            proc['stime'] = int(proc_info[14])
            # 如果该进程是老进程
            if proc['pid'] in procs.keys():
                old_proc_time = procs[proc['pid']]['utime'] + procs[proc['pid']]['stime']
                new_proc_time = proc['utime'] + proc['stime']
                proc['delta_time'] = new_proc_time - old_proc_time
            # 该进程是新进程
            else:
                proc['delta_time'] = 0
            # 更新进程信息
            procs[proc['pid']] = proc
    return procs


if __name__ == '__main__':
    second = 1

    old_cpu_time = get_cpu_time()
    old_procs = {}

    print("timestamp".ljust(20, " "), "pid".ljust(8, " "), "cpu_rate".ljust(20, " "), "process".ljust(20, " "))

    while(True):
        # 2s 测一次
        time.sleep(2*second)

        # cpu运行时间
        new_cpu_time = get_cpu_time()
        total_delta_time = (new_cpu_time - old_cpu_time)
        old_cpu_time = new_cpu_time

        # 遍历进程字典，获得每个进程运行时间，计算cpu占用率
        new_procs = get_proc_info(old_procs)
        old_procs = new_procs
        for pid in new_procs.keys():
            proc_delta_time = new_procs[pid]['delta_time']
            cpu_rate = proc_delta_time/total_delta_time
            if cpu_rate > 0.01 :
                print(str(time.time()).ljust(20, " "), str(pid).ljust(8, " "), 
                        str(cpu_rate).ljust(20, " "), new_procs[pid]['cmdline'].ljust(20, " "))



